package pers.cz.filter;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Iterator;

/**
 * 权限管理决断器
 * @program: springSecurity
 * @description: CustomAccessDecisionManager
 * @author: Cheng Zhi
 * @create: 2021-04-18 00:01
 **/
@Service
public class CustomAccessDecisionManagertest implements AccessDecisionManager {

    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {

        if (collection == null) {
            return;
        }

        Iterator<ConfigAttribute> iterators = collection.iterator();
        while (iterators.hasNext()) {
            ConfigAttribute configAttribute = iterators.next();
            // 访问资源需要的权限
            String needRole = configAttribute.getAttribute();
            // 用户目前的权限
            for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
                if (needRole.equals(grantedAuthority.getAuthority())) {
                    return;
                }
            }
            throw new RuntimeException("权限不足");
        }



    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
